package cn.tedu._07weibopjt.base.exception;

import cn.tedu._07weibopjt.base.response.JsonResult;
import cn.tedu._07weibopjt.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException illegalArgumentException) {
        log.error("IllegalArgumentException:{}", illegalArgumentException.getMessage());
        return JsonResult.fail(illegalArgumentException.getMessage());
    }
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        log.error("MethodArgumentNotValidException:{}", exception.getMessage());
        return new JsonResult(StatusCode.VALIDATED_ERROR, exception.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler
    public JsonResult doHandleMethodConstraintViolationException(ConstraintViolationException e) {
        log.error("ConstraintViolationException:{}", e.getMessage());
        return new JsonResult(StatusCode.VALIDATED_ERROR, e.getMessage().split(": ")[1]);
    }


//    @ExceptionHandler
//    public JsonResult doHandlerThrowable(Throwable throwable) {
//        log.error("Throwable:{}", throwable.getMessage());
//        return JsonResult.fail(throwable.getMessage());
//    }
}
